package com.yhq.ojbackendquestionservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhq.ojbackendcommon.common.ErrorCode;
import com.yhq.ojbackendcommon.exception.BusinessException;
import com.yhq.ojbackendquestionservice.mapper.QuestionSubmitMapper;
import com.yhq.ojbackendquestionservice.service.QuestionService;
import com.yhq.ojbackendquestionservice.service.QuestionSubmitService;
import com.yhq.ojbackendserviceclient.service.JudgeFeignClient;
import com.yhq.ojbackendserviceclient.service.UserFeignClient;
import com.yhq.ojbackendmodel.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.yhq.ojbackendmodel.model.dto.questionsubmit.QuestionSubmitRequest;
import com.yhq.ojbackendmodel.model.entity.Question;
import com.yhq.ojbackendmodel.model.entity.QuestionSubmit;
import com.yhq.ojbackendmodel.model.entity.User;
import com.yhq.ojbackendmodel.model.enums.QuestionSubmitLanguageEnum;
import com.yhq.ojbackendmodel.model.vo.QuestionSubmitVO;
import com.yhq.ojbackendmodel.model.vo.UserVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Henry
 * @description 针对表【question_submit(用户提交)】的数据库操作Service实现
 * @createDate 2023-08-20 11:47:42
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
        implements QuestionSubmitService {
    @Resource
    QuestionService questionService;
    @Resource
    UserFeignClient userFeignClient;
    @Resource
    @Lazy
    JudgeFeignClient judgeFeignClient;


    @Override
    public long questionSubmit(QuestionSubmitRequest questionSubmitRequest, User loginUser) {
        // 判断实体是否存在，根据类别获取实体
        Long questionId = questionSubmitRequest.getQuestionId();
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        long userId = loginUser.getId();
        String language = questionSubmitRequest.getLanguage();
        QuestionSubmitLanguageEnum enumByValue = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if (enumByValue == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言错误");
        }
        String code = questionSubmitRequest.getCode();
        String content = questionSubmitRequest.getContent();
        String tags = questionSubmitRequest.getTags();
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setLanguage(language);
        questionSubmit.setCode(code);
        questionSubmit.setContent(content);
        questionSubmit.setStatus(0);
        questionSubmit.setTags(tags);
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
//        todo 如何修改
        questionSubmit.setJudgeInfo("");
        boolean save = this.save(questionSubmit);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据插入异常");
        }


//        todo 加入限流机制：短时间内同一用户只能产生一条数据
//        boolean result = questionService.save(questionSubmit);
//        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return questionSubmit.getId();
    }

    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        if (questionSubmitQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = questionSubmitQueryRequest.getId();
        String language = questionSubmitQueryRequest.getLanguage();
        String content = questionSubmitQueryRequest.getContent();
        String tags = questionSubmitQueryRequest.getTags();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long userId = questionSubmitQueryRequest.getUserId();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
//        long current = questionSubmitQueryRequest.getCurrent();
//        long pageSize = questionSubmitQueryRequest.getPageSize();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(StringUtils.isNotBlank(content), "content", content);
        queryWrapper.eq(StringUtils.isNotBlank(tags), "tags", tags);
        queryWrapper.eq(userId != null, "userId", userId);
        queryWrapper.eq(questionId != null, "questionId", questionId);
        queryWrapper.eq(status != null, "status", status);


        return queryWrapper;
    }

    /**
     * 问题提交 可以查询所有用户的提交信息
     * @param questionSubmit
     * @param loginUser
     * @return
     */
    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSUbmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        // 1. 关联查询用户信息
        Long userId = questionSubmit.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userFeignClient.getById(userId);
        }
        UserVO userVO = userFeignClient.getUserVO(user);
        questionSUbmitVO.setUserVO(userVO);
        // 2. 脱敏：代码仅本人和管理员可见
        if(!userFeignClient.isAdmin(loginUser) && !loginUser.getId().equals(userId )){
            questionSUbmitVO.setCode(null);
        }
        return questionSUbmitVO;
    }
    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollectionUtils.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }

        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser))
                .collect(Collectors.toList());
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }

}




